package cn.yh.shop.admin.shiro;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import cn.yh.shop.admin.action.AdminAction;
import cn.yh.shop.admin.model.Admin;
import cn.yh.shop.admin.model.Menu;
import cn.yh.shop.admin.service.IAdminService;
import cn.yh.shop.admin.service.IMenuService;

/** 
*@Description:权限realm
* @author  "许荣斐"
* @time:2016年12月20日 下午2:33:30
* @version 1.0 
*/
public class AdminRealm extends AuthorizingRealm{
	@Autowired
    private IAdminService adminService;
    @Autowired
    private IMenuService menuService;
    
	/**
	 * @Description: logger : logger日志
	 */
	private static Logger logger = LogManager.getLogger(AdminRealm.class);
    
    /**
     * 授权(验证权限时调用)
     */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Admin user = (Admin)principals.getPrimaryPrincipal();
		logger.info("授权时:"+user);
		Integer userId = user.getId();
		
		List<String> permsList = null;
		
		//系统管理员，拥有最高权限
		if(userId == 2){
			List<Menu> menuList = menuService.queryList(new HashMap<String, Object>());
			permsList = new ArrayList<>(menuList.size());
			for(Menu menu : menuList){
				permsList.add(menu.getPerms());
			}
		}else{
			permsList = adminService.queryAllPerms(userId);
		}

		//用户权限列表
		Set<String> permsSet = new HashSet<String>();
		for(String perms : permsList){
			if(StringUtils.isBlank(perms)){
				continue;
			}
			permsSet.addAll(Arrays.asList(perms.trim().split(",")));
		}
		
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(permsSet);
		return info;
	}

	/**
	 * 认证(登录时调用)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());
        
        //查询用户信息
        Admin user = adminService.queryByUserName(username);
        logger.info("登录认证:"+user);
        //账号不存在
        if(user == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }
        
        //密码错误
        if(!password.equals(user.getPwd())) {
            throw new IncorrectCredentialsException("账号或密码不正确");
        }
        
        //账号锁定
        if(user.getStatus() == 0){
        	throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
        return info;
	}
}
